from flask import Flask, render_template, jsonify, request
import os
import shutil
import subprocess
from pathlib import Path

app = Flask(__name__)

def get_directory_contents(path, recursive=False):
    contents = []
    try:
        for item in os.scandir(path):
            item_info = {
                'name': item.name,
                'path': str(Path(item.path).relative_to(path)),
                'is_dir': item.is_dir(),
                'size': os.path.getsize(item.path) if not item.is_dir() else None,
                'modified': os.path.getmtime(item.path)
            }
            if recursive and item.is_dir():
                item_info['children'] = get_directory_contents(item.path, recursive)
            contents.append(item_info)
    except Exception as e:
        return {'error': str(e)}
    return sorted(contents, key=lambda x: (not x['is_dir'], x['name'].lower()))

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/api/list')
def list_directory():
    path = request.args.get('path', '')
    side = request.args.get('side', 'source')
    recursive = request.args.get('recursive', 'false').lower() == 'true'
    
    base_path = os.path.join(os.getcwd(), 'source' if side == 'source' else 'destination')
    full_path = os.path.join(base_path, path.lstrip('/'))
    
    contents = get_directory_contents(full_path, recursive)
    return jsonify(contents)

@app.route('/api/copy', methods=['POST'])
def copy_item():
    data = request.json
    source_path = data.get('source')
    dest_path = data.get('destination')
    direction = data.get('direction')

    if direction == 'to_right':
        src_base = os.path.join(os.getcwd(), 'source')
        dst_base = os.path.join(os.getcwd(), 'destination')
    else:
        src_base = os.path.join(os.getcwd(), 'destination')
        dst_base = os.path.join(os.getcwd(), 'source')

    # 处理路径中的中文字符
    source_path = os.path.normpath(source_path) if source_path else ''
    dest_path = os.path.normpath(dest_path) if dest_path else ''

    full_source = os.path.join(src_base, source_path.lstrip('/'))
    
    # 如果目标路径为空，使用源文件的完整相对路径
    if not dest_path:
        dest_path = source_path
    full_dest = os.path.join(dst_base, dest_path.lstrip('/'))

    try:
        # 验证源文件/目录是否存在
        if not os.path.exists(full_source):
            return jsonify({'error': f'源文件或目录不存在: {source_path}'}), 404

        print(f"正在复制: {full_source} -> {full_dest}")  # 调试日志

        # 确保目标目录存在
        if os.path.isdir(full_source):
            # 对于目录，使用shutil.copytree
            if os.path.exists(full_dest):
                shutil.rmtree(full_dest)
            shutil.copytree(full_source, full_dest)
            print(f"目录复制成功: {full_source} -> {full_dest}")
        else:
            # 对于文件，确保目标目录存在并使用shutil.copy2
            os.makedirs(os.path.dirname(full_dest), exist_ok=True)
            shutil.copy2(full_source, full_dest)
            print(f"文件复制成功: {full_source} -> {full_dest}")
            
        return jsonify({'success': True, 'output': '复制完成'})
    except Exception as e:
        error_msg = f"复制失败: {str(e)}"
        print(error_msg)  # 调试日志
        return jsonify({'error': error_msg}), 500

@app.route('/api/delete', methods=['POST'])
def delete_item():
    data = request.json
    path = data.get('path')
    side = data.get('side')
    
    base_path = os.path.join(os.getcwd(), 'source' if side == 'source' else 'destination')
    full_path = os.path.join(base_path, path.lstrip('/'))
    
    try:
        if os.path.isdir(full_path):
            shutil.rmtree(full_path)
        else:
            os.remove(full_path)
        return jsonify({'success': True})
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/delete-by-name', methods=['POST'])
def delete_by_name():
    data = request.json
    filename = data.get('filename')
    side = data.get('side')
    recursive = data.get('recursive', False)
    
    if not filename:
        return jsonify({'error': '请提供文件名'}), 400
    
    base_path = os.path.join(os.getcwd(), 'source' if side == 'source' else 'destination')
    deleted_files = []
    errors = []

    def delete_matching_files(current_path):
        try:
            for item in os.scandir(current_path):
                try:
                    if item.is_file() and item.name == filename:
                        os.remove(item.path)
                        deleted_files.append(os.path.relpath(item.path, base_path))
                    elif item.is_dir() and recursive:
                        delete_matching_files(item.path)
                except Exception as e:
                    errors.append(f"{item.path}: {str(e)}")
        except Exception as e:
            errors.append(f"{current_path}: {str(e)}")

    delete_matching_files(base_path)
    
    return jsonify({
        'success': True,
        'deleted_files': deleted_files,
        'errors': errors
    })

@app.route('/api/create-folder', methods=['POST'])
def create_folder():
    data = request.json
    folder_name = data.get('name')
    side = data.get('side')
    parent_path = data.get('parent_path', '')
    
    if not folder_name:
        return jsonify({'error': '请提供文件夹名称'}), 400
    
    base_path = os.path.join(os.getcwd(), 'source' if side == 'source' else 'destination')
    full_path = os.path.join(base_path, parent_path.lstrip('/'), folder_name)
    
    try:
        os.makedirs(full_path, exist_ok=True)
        return jsonify({'success': True})
    except Exception as e:
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    # 确保source和destination目录存在
    os.makedirs('source', exist_ok=True)
    os.makedirs('destination', exist_ok=True)
    # 在Docker中监听所有接口，使用3000端口
    app.run(host='0.0.0.0', port=3000, debug=False)